const express = require('express');
const router = express.Router();
const { authenticateToken } = require('../middleware/auth');
const { createOrder, getOrders, getOrderDetails, updateOrderStatus } = require('../models/orderModel');

// 创建订单
router.post('/', authenticateToken, async (req, res) => {
    try {
        const orderId = await createOrder(req.user.id, req.body);
        res.status(201).json({ message: '订单创建成功', orderId });
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

// 获取用户订单列表
router.get('/', authenticateToken, async (req, res) => {
    try {
        const orders = await getOrders(req.user.id);
        res.json(orders);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// 获取订单详情
router.get('/:id', authenticateToken, async (req, res) => {
    try {
        const order = await getOrderDetails(req.params.id);
        if (!order) {
            return res.status(404).json({ error: '订单不存在' });
        }
        res.json(order);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// 取消订单
router.post('/:id/cancel', authenticateToken, async (req, res) => {
    try {
        await updateOrderStatus(req.params.id, 'cancelled');
        res.json({ message: '订单已取消' });
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

// 支付订单
router.post('/:id/pay', authenticateToken, async (req, res) => {
    try {
        await updateOrderStatus(req.params.id, 'paid');
        res.json({ message: '支付成功' });
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

module.exports = router; 